package org.example.nettydemo.netty.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Scanner;

public class TcpServerHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(TcpServerHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf= (ByteBuf)msg;
        byte[] body=new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(body);
        System.out.println(new String(body));

//        System.out.println(Runtime.getRuntime().availableProcessors());
//        byte[] responseBytes = "hi,客户端,我是服务端".getBytes();
//        ctx.channel().writeAndFlush(Unpooled.wrappedBuffer(responseBytes));

        Channel channel = ctx.channel();

        logger.debug("线程启动");
        // 启动一个线程处理用户输入
        new Thread(() -> {
            try (Scanner scanner = new Scanner(System.in)) {
                while (true) {
                    System.out.print("Enter response (type 'break' to exit): ");
                    String line = scanner.nextLine();
                    if ("break".equalsIgnoreCase(line)) {
                        channel.close();
                        break;
                    }
                    byte[] responseBytes = line.getBytes(CharsetUtil.UTF_8);
                    channel.writeAndFlush(Unpooled.wrappedBuffer(responseBytes));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();

        ChannelFuture closeFuture = channel.closeFuture();
        // 同步关闭线程
//        channelFuture.sync();

        // 异步关闭线程
        closeFuture.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                logger.debug("结束之后的操作");
                System.out.println("结束之后的操作");
            }
        });

    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
    }
}
